#!/bin/bash

# 定义jar包名称和目录
JAR_NAME="java8090.jar"
JAR_DIR="/home/du/桌面"

# 重启尝试次数（这个变量将在cron中每次运行时重置）
RESTART_ATTEMPTS=0
# 最大重启尝试次数
MAX_RESTART_ATTEMPTS=3
# 重启检查间隔时间（秒）
SLEEP_DURATION=5

# 检查Java程序的文件是否存在
if [ ! -f "$JAR_DIR/$JAR_NAME" ]; then
    echo "$(date) - $JAR_DIR/$JAR_NAME does not exist. Sending email."
    /home/du/桌面/sendmail.sh "Jar不存在" "$JAR_DIR/$JAR_NAME 不存在，无法启动。"
    exit 1
fi

# 检查Java程序是否在运行
if pgrep -f $JAR_NAME > /dev/null; then
    echo "$(date) - $JAR_NAME is running."
else
    echo "$(date) - $JAR_NAME is not running. Attempting to restart..."

    # 尝试启动Java程序
    nohup java -jar $JAR_DIR/$JAR_NAME > /dev/null 2>&1 &

    # 等待一段时间后检查Java程序是否成功启动
    for (( ATTEMPT=1; ATTEMPT<=MAX_RESTART_ATTEMPTS; ATTEMPT++ )); do
        sleep $SLEEP_DURATION
        if pgrep -f $JAR_NAME > /dev/null; then
            echo "$(date) - $JAR_NAME started successfully on attempt $ATTEMPT."
            break
        else
            let RESTART_ATTEMPTS+=1
            echo "$(date) - Failed to start $JAR_NAME. Attempt $RESTART_ATTEMPTS."
        fi
    done

    # 如果重启尝试次数超过最大限制，则停止监控并发送邮件
    if [ "$RESTART_ATTEMPTS" -ge "$MAX_RESTART_ATTEMPTS" ]; then
        echo "$(date) - $JAR_NAME failed to start after $MAX_RESTART_ATTEMPTS attempts. Stopping monitoring and sending email."
        /home/du/桌面/sendmail.sh "重启失败" "$JAR_NAME重启失败，已达到最大尝试次数，不再尝试重启。"
        exit 1
    fi
fi
